package com.web.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;

/**
 * 自定义随机算法
 * balancer 平衡器
 *
 */
public class RandomRule_ZY extends AbstractLoadBalancerRule {
    Random rand;
    public RandomRule_ZY(){
        rand = new Random();
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
    //分析
    //total = 0;//当total==5以后，指针往下走
    //index = 0;//当前对外提供服务的服务器地址，即total=5,index++，total=0;
    //index不能超过总机器数
    private int total = 0;//总共被调用的次数，目前要求每台被调用5次
    private int currentIndex = 0;//当前提供服务的机器号

    public Server choose(ILoadBalancer lb,  Object key){
        if (lb == null){
            return null;
        }
        Server server = null;

        while (server == null){
            if(Thread.interrupted()){
                return null;
            }
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if(serverCount == 0){
                return null;
            }

            /*int index = rand.nextInt(serverCount);//在已有的server中随机一个
            server = upList.get(index);*/

            if(total<5){
                server = upList.get(currentIndex);
                total++;
            } else {
                total = 0;
                currentIndex++;
                if(currentIndex>=upList.size()){
                    currentIndex = 0;
                }
            }

            if(server == null){
                Thread.yield();//线程中断一会
                continue;
            }
            if(server.isAlive()){
                return server;
            }
            server = null;
            Thread.yield();
        }
        return null;
    }

    @Override
    public Server choose(Object o) {
        return null;
    }
}
